/**
 * Copyright (c) 2006-2008, Julien PORTALIER
 * 
 * Licensed under The LGPL License
 * Redistributions of files must retain the above copyright notice.
 * 
 * @copyright  Copyright (c) 2006-2008, Julien PORTALIER
 * @link       http://feather-cm.google.com/
 * @license    http://www.opensource.org/licenses/lgpl-license.php The LGPL License
 */

var Windows = {};

Windows.Sticky = new Class(
{
	initialize: function(url, options)
	{
		this.options = {
			'id':        'window',
			'className': 'window-sticky',
			'title':     'Window',
			'callback':  Class.empty
		};
		this.setOptions(options);
		
		// window
		this.window = new Element('div', {
			'id':    this.options.id,
			'class': this.options.className
		});
		
		// titlebar
		var titlebar = new Element('p', {'class': 'title'}).setText(this.options.title);
		var close = new Element('a', {
			'class': 'close',
			'href': '#',
			'title': _('Click to close')
		}).setText('X').addEvent('click', this.hide.bindWithEvent(this));
		titlebar.appendChild(close);
		this.window.appendChild(titlebar);
		
		// content
		this.content = new Element('div', {'class': 'content'});
		this.fillContent(url);
		this.window.appendChild(this.content);
		
		// display
		this.setPosition();
		document.body.appendChild(this.window);
	},
	
	fillContent: function(url, method)
	{
		url = url || this.url;
		this.url = url;
		this.request('get', url);
	},
	
	replaceContentWith: function(html)
	{
		this.content.setHTML(html);
		this.routeLinks();
	},
	
	request: function(method, url, data)
	{
		// cancel previous request
		if (this.ajax)
			this.ajax.cancel();
		
		// request content
		this.ajax = new Ajax(url, {
			'method':     method,
			'update':     this.content,
			'onComplete': this.routeLinks.bind(this)
		}).request(data);
	},
	
	routeLinks: function()
	{
		$ES('a', this.content).each(function(a)
		{
			if (!a.hasClass('noroute')) {
				a.addEvent('click', this.followLink.bindWithEvent(this));
			}
		}, this);
		this.options.callback(this.content);
	},
	
	followLink: function(evt)
	{
		evt.stop();
		this.fillContent(evt.target.getAttribute('href'));
	},
	
	setPosition: function(top, left)
	{
		top  = top  || document.documentElement.scrollTop;
		left = left || document.documentElement.scrollLeft;
		this.window.setStyles({
			'left': left + 28 + 'px',
			'top':  top  + 28 + 'px'
		});
	},
	
	hide: function(evt)
	{
		this.window.setStyle('display', 'none');
		if (evt)
			evt.stop();
	},
	
	show: function()
	{
		this.setPosition();
		this.window.setStyle('display', '');
	}	
});
Windows.Sticky.implement(new Options());
